package com.cx.algrithm.leetcode.day1;

/**
 * @Author songyahui
 * @Date 2023/9/12 12:02
 * @Description
 */

import java.math.BigInteger;

class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode node1 = solution.getLinksRandom();
        solution.printNodeInfo(node1);
        ListNode node2 = solution.getLinksRandom();
        solution.printNodeInfo(node2);
        ListNode nodeSum = solution.subtractTwoNumbers(node1, node2);
        solution.printNodeInfo(nodeSum);
    }

    class ListNode {
        private long val;
        private ListNode pre;
        private ListNode next;

        ListNode(int val) {
            this.val = val;
        }

        ListNode() {
        }
    }

    public ListNode subtractTwoNumbers(ListNode l1, ListNode l2) {
        //用于依次添加节点
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        //得到两数相碱后的值
        BigInteger b1 = new BigInteger("" + replace(s1, l1)).subtract(new BigInteger("" + replace(s2, l2)));
        //把b1 转为字符串操作
        String s = "" + b1.abs();
        System.out.println("out:" + s);

        System.out.println("out:" + s.toCharArray().length);
        //新建链表
        ListNode head = this.new ListNode(s.charAt(0));
        ListNode headCopy = head;
        System.out.println("head:" + head.val);
        ListNode l = null;
        //依次添加字符串数据
        for (int i = 1; i < s.length(); i++) {
            l = new ListNode(s.charAt(i));
            add(headCopy, l);
            headCopy = l;
        }
        //返回头节点
        return head;
    }

    //循环向StringBuilder里面添加内容
    public StringBuilder replace(StringBuilder s, ListNode l) {
        boolean flag = true;
        while (flag) {
            if (l != null) {
                s.append(l.val);
                l = l.next;
            } else {
                flag = false;
            }
        }
        return s;
    }

    ListNode getLinksRandom() {
        ListNode node = this.new ListNode();
        for (int i = 0; i < 2; i++) {
            if (node.val <= 0) {
                node.val = Math.round(Math.random() * 10);
            }
            ListNode newNode = this.new ListNode();
            newNode.val = Math.round(Math.random() * 10);
            this.add(node, newNode);
            node = newNode;
        }
        return node;
    }

    //顺序插入
    public void add(ListNode head, ListNode l) {
        while (head.pre != null) {
            head = head.pre;
        }
        head.pre = l;
        l.next = head;
    }

    void printNodeInfo(ListNode node) {
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }
}
